package com.elock.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Repository;

import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.dao.impl.DaoCenter;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.DateUtil;
import com.elock.base.core.util.WebUtils;

/**
 * Dao - 电子围栏
 * @author 仁德
 */
@Repository("electronicFenceDao")
public class ElectronicFenceDao extends DaoCenter {

//	@Resource(name = "saleOrgBaseServiceImpl")
//	private SaleOrgBaseService saleOrgBaseService;

	public Page<Map<String, Object>> findPage(String name, Integer type, Long saleOrgId,
			String startTime, String endTime, Pageable pageable) {

		List<Object> list = new ArrayList<Object>();
		StringBuilder sql = new StringBuilder();
		Long companyInfoId = WebUtils.getCurrentCompanyInfoId();
		sql.append(
				"select e.*,so.name sale_org_name from electronic_fence e left join electronic_fence_sale_org efso on e.id=efso.electronic_fence_id");
		sql.append(" left join sale_org so on so.id=efso.sale_org_id where 1=1");
		if (companyInfoId != null) {
			sql.append(" and e.company_info_id=?");
			list.add(companyInfoId);
		}
		if (!ConvertUtil.isEmpty(name)) {
			sql.append(" and e.name like ?");
			list.add("%" + name + "%");
		}
		if (type != null) {
			sql.append(" and e.type=?");
			list.add(type);
		}
		if (saleOrgId != null) {
			sql.append(" and so.id=?");
			list.add(saleOrgId);
		}
		if (!ConvertUtil.isEmpty(startTime)) {
			sql.append(" and e.create_date >= ?");
			list.add(DateUtil.convert(startTime + " 00:00:00"));
		}
		if (!ConvertUtil.isEmpty(endTime)) {
			sql.append(" and e.create_date < ?");
			list.add(DateUtils.addDays(DateUtil.convert(endTime + " 00:00:00"), 1));
		}
//		sql.append(" and so.id in (" + saleOrgBaseService.saleOrgAuth() + ")");

		sql.append(" order by e.create_date desc");

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}

		Page<Map<String, Object>> getPage = getNativeDao().findPageMap(sql.toString(),
				objs,
				pageable);

		return getPage;

	}
}